<template>
  <div>
    <van-cell v-for="item in suggestions" :key="item" icon="search" @click="onSearch(item)">
      <template #title>
        <div v-html="highText(item)"></div>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  beforeDestroy () { // 组件销毁的时候执行钩子，将最后一次定时器销毁
    clearTimeout(this.setid)
  },
  watch: {
    searchText: {
      immediate: true,
      handler (newval) {
        if (this.setid) { // 如果this.setid里有之前的定时器，那就将它清除
          clearTimeout(this.setid)
        }
        this.setid = setTimeout(async () => { // 将定时器挂在this上，setId
          const res = await getSearchSuggestion(newval)
          this.suggestions = res.options
        }, 700)
      }
    }
  },

  data () {
    return {
      suggestions: []
    }
  },

  created () {

  },

  methods: {
    highText (item) {
      const replaceStr = '<span style="color: red">' + this.searchText + '</span>'
      // replace方法，第一个参数是要被替换的内容，第二个参数是替换后的内容
      const reg = new RegExp(this.searchText, 'gi') // 动态正则构造函数RegExp g是全局匹配 i是忽略大小写
      return item.replace(reg, replaceStr)
      // return 123
    },
    onSearch (item) {
      this.$emit('on-search', item)
    }
  }
}
</script>

<style scoped lang='less'>

</style>
